

<template>
  <li>
    <label>
      <input
        type="checkbox"
        :checked="todo.done"
        @change="checkboxChange(todo.id)"
      />
      <span v-show="!todo.isEdit">{{todo.name}}</span>
      <input
        type="text"
        ref="editRef"
        v-show="todo.isEdit"
        :value="todo.name"
        @blur="handleBlur(todo,$event)"
        @keyup.enter="handleBlur(todo,$event)"
      >
    </label>
    <button
      class="btn btn-danger"
      @click="deleteTodo(todo.id)"
    >删除</button>
    <button
      class="btn btn-edit"
      @click="updateTodo(todo)"
      v-show="!todo.isEdit"
    >编辑</button>
  </li>
</template>

<script>
import pubsub from 'pubsub-js'

export default {
  name: 'MyItem',
  props: ['todo'],
  methods: {
    checkboxChange (id) {
      // 获取当前checkbox状态
      console.log(id)
      this.$bus.$emit('updateTodoCheck', id)
    },
    deleteTodo (id) {
      console.log(id)
      confirm(`确定删除id为${id}的元素?`) && pubsub.publish('filterTodos', id)
    },
    updateTodo (todo) {
      if (Object.prototype.hasOwnProperty.call(todo, 'isEdit')) {
        // todo.hasOwnProperty('isEdit') eslint关了可以这么写
        this.todo.isEdit = true
      } else {
        // 不想直接修改他
        // this.$set(todo, 'isEdit', true) 
        this.$bus.$emit('updateTodoIsEdit', todo)
      }
      
      console.log(this.$refs.editRef)
      //这么写不vue
      // setTimeout(()=>this.$refs.editRef.focus(),500)
      this.$nextTick(()=>this.$refs.editRef.focus())
      // (todo.isEdit===null||todo.isEdit===undefined)?this.$set(todo, 'isEdit', true):(this.todo.isEdit=true)
    },
    //失去焦点回调(真正执行修改逻辑)
    handleBlur (todo, e) {
      todo.isEdit = false;
      // console.log(todo.id,e.target.value);
      if (!e.target.value) { alert('输入不能为空'); return }
      this.$bus.$emit('updateTodoEdit', todo.id, e.target.value)
    }

  }
}
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover {
  background-color: #ccc;
}
li:hover button {
  display: block;
}
</style>